<template>
    <div class="map">
        <div id="container"></div>
        <img ref="addbtn" class="addBtn" src="../common/img/Map/add.png" alt="" @click="touchbtn">
        <van-popup v-model:show="showBottom" round position="bottom"
            :style="{ height: `${popupHeight}`, transition: 'all 0.5s' }" :overlay="false">
            <h1>添加目标地点</h1>
            <van-search v-model="searchValue" show-action label="地址" placeholder="请输入搜索关键词" shape="round">
            </van-search>
            <van-cell-group>
                <van-cell :title="item.title" :value="item.province ? item.province + '-' + item.city : ''"
                    :label="item.address" v-for="item in searchList" :key="item.uid" @click="addPoint(item)" />
            </van-cell-group>
        </van-popup>
        <!-- 遮罩层 -->
        <van-overlay :show="showOverlay" @click="show = false" style="z-index: 999;">
            <div class="wrapper" @click.stop>
                <h1>加载中...</h1>
                <div class="block">
                    <img src="../common/img/Map/loading.gif" alt="">
                </div>
            </div>
        </van-overlay>
    </div>
</template>
<script lang="ts">
export default {
    name: 'BaiduMapView',
}
</script>
<script setup lang="ts">
import { inject, onMounted, reactive, ref, watch } from "vue";
import { usePointStore } from '@/stores/modules/pointStore'
let BMapGL: any;
const map: any = inject('map');
const markerList: any = inject('markerList');
const showBottom = ref(false);//显示添加菜单
const addbtn = ref(0);
const searchValue = ref('')
const searchList = ref([])
const popupHeight = ref('50%')
const showOverlay = ref(false);
const pointStore: any = usePointStore();
//创建地图
onMounted(() => {
    BMapGL = window.BMapGL;
    map.value = new BMapGL.Map("container", {
        coordsType: 5, showControls: true, minZoom: 1
        // coordsType指定输入输出的坐标类型，3为gcj02坐标，5为bd0ll坐标，默认为5。
        // 指定完成后API将以指定的坐标类型处理您传入的坐标
    });
    pointStore.map = map;

    map.value.setMapType(window.BMAP_EARTH_MAP)
    map.value.centerAndZoom(new BMapGL.Point(-16.32723583996417, 12.059617810228133), 3);
    map.value.enableScrollWheelZoom(true);
    map.value.enablePinchToZoom(true);
    map.value.addControl(new BMapGL.ZoomControl());
    const locationControl = new BMapGL.LocationControl({
        // 控件的停靠位置（可选，默认左上角）
        anchor: window.BMAP_ANCHOR_TOP_RIGHT,
        // 控件基于停靠位置的偏移量（可选）
        offset: new BMapGL.Size(20, 20)
    });
    // 将控件添加到地图上
    map.value.addControl(locationControl);
    // 添加地点;
    //监听地图点击事件
    map.value.addEventListener('click', () => {
        showBottom.value = false;
    }
    );

    //添加节点
    pointStore.pointList.forEach(item => { createdPoint(item.val, 3) })
    setTimeout(() => {
        createdStart();
        getPosition();
    }, 2000)
    createControl()
})
//定义一个控件类
function ZoomControl() {
    this.defaultAnchor = window.BMAP_ANCHOR_TOP_LEFT;
    this.defaultOffset = new BMapGL.Size(20, 20)
}
//添加控件
let mapType = 1;
const createControl = () => {

    //通过JavaScript的prototype属性继承于BMap.Control
    ZoomControl.prototype = new BMapGL.Control();

    //自定义控件必须实现自己的initialize方法，并且将控件的DOM元素返回
    //在本方法中创建个div元素作为控件的容器，并将其添加到地图容器中
    ZoomControl.prototype.initialize = function () {
        //创建一个dom元素
        const div = document.createElement('div');
        //添加文字说明
        div.appendChild(document.createTextNode(mapType == 1 ? '切换2D地图' : '切换卫星地图'));
        // 设置样式
        div.style.cursor = "pointer";
        div.style.padding = "7px 10px";
        div.style.boxShadow = "0 2px 6px 0 rgba(27, 142, 236, 0.5)";
        div.style.borderRadius = "5px";
        div.style.backgroundColor = "white";
        // 绑定事件,点击一次放大两级
        div.onclick = function (e) {
            if (mapType == 1) {
                map.value.setMapType(window.BMAP_NORMAL_MAP);
                mapType = 2;
            }
            else {
                map.value.setMapType(window.BMAP_EARTH_MAP);
                mapType = 1
            }
        }
        // 添加DOM元素到地图中
        map.value.getContainer().appendChild(div);
        // 将DOM元素返回
        return div;
    }
    //创建控件元素
    const myZoomCtrl = new ZoomControl();
    //添加到地图中
    map.value.addControl(myZoomCtrl);
}
//创建开始点
const createdStart = (startPoint: any) => {
    //创建开始节点

    const point = startPoint || new BMapGL.Point(114.432244, 30.613334);
    map.value.panTo(point)
    setTimeout(() => {
        map.value.setZoom(14, { noAnimation: false });
    }, 1000)
    createdPoint({ point: point, title: '起点', message: '从这里开始一段美妙的旅行' }, 1)
}
//设置搜索

const searchUpdate = async (newVal: any) => {
    popupHeight.value = "50%";
    const local = new BMapGL.LocalSearch(map.value, {
        onSearchComplete: function (results) {
            // 判断状态是否正确
            const lsSearch = [];
            if (local.getStatus() == window.BMAP_STATUS_SUCCESS) {

                for (let i = 0; i < results.getCurrentNumPois(); i++) {
                    lsSearch.push(results.getPoi(i));
                }
                searchList.value = lsSearch;
            }
            else {
                searchList.value = []
                console.log("搜索错误")
            }
        }
    });
    local.search(searchValue.value);
    local.search(searchValue.value);
}


//点击img按钮
const touchbtn = () => {
    showBottom.value = true;
}
//按钮单元格添加节点
const addPoint = (item) => {
    map.value.panTo(item.point)
    if (!pointStore.pointList.some((i) => i.val.uid == item.uid)) {
        createdPoint(item, 2)
    }
    popupHeight.value = '30%'

}
//添加节点   
// type=1开始节点
// type=2正常节点
// type=3起始节点列表
function createdPoint(item, type = 2) {
    let myIcon: any;
    if (type == 1)
        myIcon = new BMapGL.Icon(new URL('../common/img/Map/start.png', import.meta.url).href, new BMapGL.Size(52, 52));
    else {
        myIcon = new BMapGL.Icon(new URL('../common/img/Map/camera.png', import.meta.url).href, new BMapGL.Size(52, 52));
    }
    const startPos = new BMapGL.Marker(item.point, {
        icon: myIcon,
        title: item.title
    });
    map.value.addOverlay(startPos);
    if (type != 1)
        markerList.value.push(startPos);
    //并非初始化时，记录marker信息
    if (type == 2)
        pointStore.pointList.push({ val: item, isFinish: false })
    const opts = {
        width: 200,     // 信息窗口宽度
        height: 50,     // 信息窗口高度
        title: item.title, // 信息窗口标题
    }
    const infoWindow = new BMapGL.InfoWindow(type == 1 ? item.message : '地址：' + item.address, opts);  // 创建信息窗口对象 
    startPos.addEventListener("click", function () {
        console.log("点击")
        map.value.openInfoWindow(infoWindow, item.point); //开启信息窗口
    });
    return startPos;
}
let firstgetPosition = true;
//创建定位
let mk = null;//当前定位
function getPosition() {
    const opts = {
        width: 200,     // 信息窗口宽度
        height: 20,     // 信息窗口高度
        title: '你的位置', // 信息窗口标题
    }
    const infoWindow = new BMapGL.InfoWindow("垃圾米冲冲冲", opts);  // 创建信息窗口对象 
    const geolocation = new BMapGL.Geolocation();
    geolocation.getCurrentPosition(function (r) {
        if (this.getStatus() == window.BMAP_STATUS_SUCCESS) {
            if (mk) {
                mk.setPosition(r.point)
            }
            else {
                const myIcon = new BMapGL.Icon(new URL('../common/img/Map/people.png', import.meta.url).href, new BMapGL.Size(52, 52));
                mk = new BMapGL.Marker(r.point, {
                    icon: myIcon
                });
                mk.addEventListener("click", function () {
                    map.value.openInfoWindow(infoWindow, r.point); //开启信息窗口
                });
                map.value.addOverlay(mk);
                if (firstgetPosition) {
                    map.value.panTo(r.point);
                    showOverlay.value = false
                }
                firstgetPosition = false;
            }



        }
        else {
            console.log('failed' + this.getStatus());
        }
    })
}
//实时定位
setInterval(() => {
    getPosition();
}, 2000)
//监听添加按钮 设置图标变化
watch(showBottom, (newVal) => {
    if (newVal)
        addbtn.value.style.left = "1vh";
    else {
        addbtn.value.style.left = "-3vh";
        searchValue.value = ''
    }
})
watch(searchValue, searchUpdate)
</script>


<style lang="scss" scoped>
.wrapper {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
    flex-direction: column;
    color: #b8b9fd;
}

.block {
    width: 40vw;
    background-color: #fff;
    border-radius: 20px;
    overflow: hidden;

    img {
        width: 100%;

    }
}
</style>
